#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h> 
#include <sys/socket.h>
#include <netinet/in.h>
#include "./lib/byte_handler.h"
#include "./lib/network_handler.h"


int con_socket;

void error(const char *msg)
{
    perror(msg);
    exit(1);
}


void RecieveFile(int target_socket )
{
	int n;
	char file_buffer[1000000];

	memset(file_buffer, 0, sizeof(file_buffer));

	n = read(target_socket, file_buffer, sizeof(file_buffer));

	if (n <= 0)  
		error("read failed");
	else
		printf("Recieved : %d bytes of data\n", n);

}


int main(int argc, char *argv[])
{
	int mi_bind, mi_socket;
        int port_nr = 20000;
	struct sockaddr_in ser_addr, cl_addr;
	char buffer[256];
		
	mi_socket = socket(AF_INET, SOCK_STREAM, 0);
	

	memset(&buffer, 0, sizeof(buffer));
	memset(&cl_addr, 0, sizeof(cl_addr));
	memset(&ser_addr, 0, sizeof(ser_addr));
     	
	ser_addr.sin_family 		 = AF_INET;
	ser_addr.sin_addr.s_addr  	 = INADDR_ANY;
	ser_addr.sin_port 		 = htons(port_nr);

	// ==================================================================== //
	// 				Testing					//
	// ==================================================================== //





	// ===================================================================== //
		

	printf("Binding to socket..\n");
	if (mi_bind = bind(mi_socket, (struct sockaddr *) &ser_addr, sizeof(ser_addr)) < 0)
		error("bind failed"); 


	printf("Connected with socket descriptor: %d \n", mi_socket);
	printf("Listening on socket..\n");
	if (listen(mi_socket, 5) < 0)
		error("listen failed");
	

	int client_len = sizeof(&cl_addr);
	printf("Trying to accept call..\n");
	if ((con_socket = accept(mi_socket, (struct sockaddr *) &cl_addr, &client_len)) < 0)
		error("connection failed");
	else
		printf("Connected..\n");


	printf("Connected withh socket descriptor:  %d \n", con_socket);	
	printf("Waiting for data..\n");
	memset(&buffer, 0, 256);


	int 	n;
	
	
	printf("Recieving data..\n");
	while(1)
	{
		memset(&buffer, 0, sizeof(buffer));		
		if (RecieveMessage(con_socket, buffer) == 0)
			error("ERROR Recieving message from socket!");

		printf("Data recieved : %s",buffer);	

		/* Byte compare! */
		char *com_quit ="quit";
		char *com_file ="file";
		if (strcmp(buffer, com_quit)==0)
		{
				SendMessage(con_socket, "Closing down..");
				close(mi_socket);
				close(con_socket);
				error("QUIT SIGNAL RECIEVED!\n");
		}
		else if(strcmp(buffer,com_file)==0)
		{
				SendMessage(con_socket,"recv_succes");
				RecieveFile(con_socket); 
		}
		int i ;
	}


	return 0; 
}


